package demo30;

import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * 阅读ConcurrentSkipListMap
 * http://blog.csdn.net/sunxianghuang/article/details/52221913
 * <p>
 * 比较一下ConcurrentHashMap和Hashtable的效率
 * <p>
 * ConcurrentHashMap效率应该是比较高的，因为ConcurrentHashMap和Hashtable加锁的方式不一样。
 * Hashtable是把自己整个都加锁了，而ConcurrentHashMap是采取锁分段。
 */
public class T {
    public static void main(String[] args) {
        Map<String, String> map = new ConcurrentHashMap<>();
//        Map<String,String> map = new ConcurrentSkipListMap<>(); //高并发，排序。插入时效率比较低。查快


//        Map<String,String> map = new Hashtable<>(); // 所有操作加锁的，效率低
//        Map<String,String> map = new HashMap<>(); //没有锁，但是可以通过Collections.synchronizedXXXX去加锁
//        Map<String,String> map = new TreeMap<>();  //插入时要排序，所以插入可能会比较慢

        Random r = new Random();
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);  //门闩计数器  100
        long start = System.currentTimeMillis(); //开始时间
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {  //向map中加入1万个随机字符串
                    map.put("a" + r.nextInt(100000), "a" + r.nextInt(100000));
                }
                latch.countDown();  //每执行一个线程，就countdown一次
            });
        }
        Arrays.asList(threads).forEach(Thread::start);  //所有线程启动
        try {
            latch.await(); //主线程在这等着，直到countdown到0
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();  //结束时间
        System.out.println(end - start);  //程序执行时间
    }
}